﻿
namespace TestFsWeb

open System
open System.Net

module WebClientExtend =

    type WebClient with
        member this.AsyncDownloadData (address : string) =

            let continuation (cont,econt,ccont) =

                let subscription : IDisposable ref = ref null

                let onCompleted (evtargs: DownloadDataCompletedEventArgs )=
                    
                    if evtargs.Error <> null then
                        econt evtargs.Error
                    elif evtargs.Cancelled then
                        ccont <| new OperationCanceledException()
                    else
                        cont evtargs.Result

                    if !subscription <> null then 
                        (!subscription).Dispose()

                subscription := this.DownloadDataCompleted.Subscribe onCompleted
                this.DownloadDataAsync <| new Uri(address)

            Async.FromContinuations continuation

        member this.AsyncUploadString (address : string) (content : string) =

            let continuation (cont,econt,ccont) =
                
                let subscription : IDisposable ref = ref null

                let onCompleted (evtargs: UploadStringCompletedEventArgs) =

                    if evtargs.Error <> null then
                        econt evtargs.Error
                    elif evtargs.Cancelled then
                        ccont <| new OperationCanceledException()
                    else
                        cont evtargs.Result
                        
                    // dispose is important here
                    // because WebClient can be re-used
                    // so we have to make sure previous event handler is un-subscribed
                    if !subscription <> null then
                        (!subscription).Dispose()

                subscription := this.UploadStringCompleted.Subscribe onCompleted
                this.UploadStringAsync(new Uri(address),content)

            Async.FromContinuations continuation






            


